#!/bin/sh
NEW_VER="9"
NVM_NODE_VER=`cat .nvmrc`
VER_PATH=".initver"
VER=`[ -f "${VER_PATH}" ] && cat ${VER_PATH} || echo "1"`
echo "current version is ${VER}."


PROFILE_NAME=".bash_profile"
PROFILE_PATH="${HOME}/${PROFILE_NAME}"
touch $PROFILE_PATH

rm -f .lock

execPath() {
    eval ${EXPORT_PATH}
}


bashAddPath () {
    ( cat ${PROFILE_PATH} 2>/dev/null | grep -Fv "${EXPORT_PATH}" ; printf -- "${EXPORT_PATH}" ; echo "" ) > ${PROFILE_NAME}
    cat ${PROFILE_NAME} > ${PROFILE_PATH}
}



# install nvm
HAS_NVM=`command -v nvm`
if [ "${HAS_NVM}" = "" ]
then
echo "installing nvm..."
brew install nvm
echo "done."
fi



# install bash_profile
echo "installing PATH..."

EXPORT_PATH='export PATH=./node_modules/.bin:$PATH'
execPath
bashAddPath

EXPORT_PATH='NVM_NODEJS_ORG_MIRROR=https://npm.taobao.org/mirrors/node'
execPath
bashAddPath

EXPORT_PATH='export NVM_DIR=$HOME/.nvm'
execPath
bashAddPath

EXPORT_PATH='. /usr/local/opt/nvm/nvm.sh'
bashAddPath

EXPORT_PATH='[[ -r $NVM_DIR/bash_completion ]] && . $NVM_DIR/bash_completion'
bashAddPath

rm -f .nvmrc
echo "sourcing..."
. ${PROFILE_PATH}
echo "done."


# install node version
HAS_NODE=`nvm ls ${NVM_NODE_VER} | awk '{print $1}'`
if [ "${HAS_NODE}" = "N/A" ]
then
echo "installing node ${NVM_NODE_VER}..."
nvm install ${NVM_NODE_VER}
echo "done."
else
echo "node ${NVM_NODE_VER} already installed."
fi



#! use the project node version
echo ${NVM_NODE_VER} > .nvmrc
nvm use



# do upgrade version
if [ "${VER}" != "${NEW_VER}" ]
then
echo "upgrading version from ${VER} to ${NEW_VER}..."

# uninstall global eslint
npm uninstall \
    --silent \
    -g eslint

# install global packages
npm install \
    --silent \
    --registry=https://registry.npm.taobao.org \
    -g eslint-cli node-inspector shrinkpack bunyan

echo "done."
fi



# clean cache
echo "cleaning cache..."
rm -rf ./node_modules
echo "done."


# do work
if [ ! -f "${VER_PATH}" ]
then

# clean
echo "cleaning, please wait..."
rm -rf node_modules/

echo "no npm-shrinkwrap.json"
# install packages
echo "installing packages, please wait..."
npm install --silent --registry=https://registry.npm.taobao.org
# lock down
npm shrinkwrap
shrinkpack

echo "done."
else
echo "has npm-shrinkwrap.json"
# lock down
shrinkpack
# install packages
echo "upgrading packages, please wait..."
npm install --silent --registry=https://registry.npm.taobao.org
echo "done."
fi

# save version
VER=${NEW_VER}
echo ${VER} > ${VER_PATH}
echo "finished, ver:${VER}"